/**
 * 
 */


// Profile only!!!
SearchResultPortlet = Class.extend(
		{
			init : function() {
				this.name = "SearchResultPortlet";
				this.model = {};
				this.pageType = "";//Profile; Knowledge; 
				this.query = "";
				this.dataResJSON = null;
				this.highlightResJSON = null;
				// để biết xem thằng nào trước thằng nào sau.
				this.itemOrder = null;
				this.numDocs = null;
				this.start = null;
				this.rows = null;
				this.ajaxProfileArr = Array();
				this.root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
			},
			
			onBegin: function()	{
				this.registerObserver();
				this.prepareData();
			},
			
			// done
			prepareData: function(){
				var request = SingletonFactory.getInstance(Page).getRequest();
				var params = request.getParams();
				this.query = params['query'];
				this.pageType = params['type'];
				this.searchPage = params['search-page'] || 1;
				this.rows = params['rows'] || 10;
				this.configData = this.getConfigData();
				this.getDataFromServer();
				this.getAllKeywords();
			},
			
			getDataFromServer: function(){
				var currentPorlet = {};
				var root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
				var urlStr = root + "ajax/get-search-result/query/" + this.query + "/searchPage/" + this.searchPage + "/rows/" + this.rows;
				$.ajax({url:urlStr, async: false, success: function(ret){
						ret = $.parseJSON(ret);
						if(ret.result != undefined){
							ret = $.parseJSON(ret.result);
							currentPorlet.numDocs = ret.response.numFound;
							currentPorlet.dataResJSON = ret.response.docs;
							currentPorlet.highlightResJSON = ret.highlighting;
						} else {
							//console.log("Lỗi xảy ra");
						}
					}
				});
				
				this.numDocs = currentPorlet.numDocs;
				this.dataResJSON = currentPorlet.dataResJSON;
				this.highlightResJSON = currentPorlet.highlightResJSON;
			},
			
			// done
			// return json object
			getHighlight: function(profileID, fieldName){
				if(this.highlightResJSON[profileID] == undefined || this.highlightResJSON[profileID][fieldName] == undefined){
					return null;
				}
				return this.highlightResJSON[profileID][fieldName];
			},
			
			// done
			getConfigData: function(){
				try{
					var data = eval("(" + tmpl(this.name + "-ItemConfig" + this.pageType,{}) + ")");
					// iterate through json sent from server and build template arcording to view type
					var hashConfig = Array(); 
					// item order
					var orderItemHelper = $("<div></div>");
					for(var key in data){
						for(var k in data[key]){
							hashConfig[data[key][k].type] = key;
						}
						$(orderItemHelper).append($("<div class='"+key+"'></div>"));
					}
					this.itemOrder = $(orderItemHelper);
					return hashConfig;
				}
				catch(ex){
					//console.log("Cannot find ItemConfig" + this.pageType + " -- " + ex);
				}
				return null;
			},
			
			getAllKeywords: function(){
				var sysProp = SingletonFactory.getInstance(Application).getSystemProperties();
				if(sysProp.get("host.keywordsMap") != undefined){
					return;
				}
				
				//ajax
				$.ajax( {url:this.root + 'ajax/get-all-keywords', async:false, success:	function(ret)	{
							ret = $.parseJSON(ret);
							ret = ret.result;
							var result = Array();
							for(var key in ret){
								result[ret[key].keyword] = ret[key].content; 
							}
							sysProp.set("host.keywordsMap",result);
						}
				});
			},
			
			buildSearchItems: function(){
				var keywordsMap = SingletonFactory.getInstance(Application).getSystemProperties().get("host.keywordsMap");
				var keywordCheck = Array();
				var finalResult = Array();
				// build template for each type => single []; list []; highlightResJSON []
				var profileID = -1;
				var originalItemOrder = null;
				var originalPlhld = $(this.getSearchItemPlhld());
				var name = "";
				var linkImg = null;
				
				for(var index in this.dataResJSON) {
					//each profile goes here 
					var searchItemPlhld = $(originalPlhld).clone();
					profileID = this.dataResJSON[index].profile_id;
					this.ajaxProfileArr.push(profileID);
					originalItemOrder = this.itemOrder.clone();
					
					name = this.dataResJSON[index].name_indexed || this.dataResJSON[index].name_unindexed;
					linkImg = null;
					// preview
					for(var field in this.dataResJSON[index]){
						if(field == "profile_id"){
							continue;
						}
						
						var keyword = this.normalizeKeyword(field);
						var type = this.configData[keyword];
						
						if(keyword == "avatar"){
							linkImg = this.dataResJSON[index][field];
							continue;
						}
						 
						if(keyword == "name" ){
							var tmpName = this.getHighlight(profileID, field); 
							if(tmpName != undefined){
								name = tmpName;
							}
						}
						
						if(type != undefined){
							//check highlightResJSON for this keyword
							var hl = this.getHighlight(profileID, field); 
							if(hl != undefined){
								keywordCheck[profileID + "_" + keyword] = true;
								this.dataResJSON[index][field] = hl;
							}

							// data param to templating
							var objParams = {};
							objParams.header = keywordsMap[keyword];
							
							// if type== List => need children
							if(type == "List"){
								// find children
								var objParamsArr = Array();
								for(var k in this.dataResJSON[index][field]){
									var objParam = {};
									objParam.content = this.dataResJSON[index][field][k];
									objParamsArr.push(this.buildPartialTemplate(objParam, "ListItem"));
								}
								objParams.content = objParamsArr;
							} 
							// else just content
							else {
								objParams.content = this.dataResJSON[index][field];
							}
							
							originalItemOrder.children("." + type).append($(this.buildPartialTemplate(objParams, type)));
						}
					}
					
					$(searchItemPlhld).children(".search_result_main").children(".search_result_preview").append(originalItemOrder.children().children());
					
					// highlight
					for(var field in this.highlightResJSON[profileID]){
						var keyword = this.normalizeKeyword(field);
						if(keywordCheck[profileID + "_" + keyword] == undefined){
							var objParam = {};
							objParam.header = keywordsMap[keyword];
							objParam.content = this.highlightResJSON[profileID][field];
							$(searchItemPlhld).children(".search_result_highlight").append(this.buildPartialTemplate(objParam, "Highlight"));
						}
					}
					
					var linkProfile = "#page/ProfilePage/id/" + profileID; 
					linkImg = linkImg == null? "styles/images/unknown.png" : linkImg;
					
					var objParam = {};
					objParam.name = name;
					objParam.link = linkProfile;
					objParam.profileid = profileID;
					searchItemPlhld.children(".search_result_brief").append(this.buildPartialTemplate(objParam, "BriefInfo"));
					
					objParam = {};
					objParam.linkProfile = linkProfile;
					objParam.linkImg = linkImg;
					searchItemPlhld.children(".search_result_main").children(".search_result_pic").append($(tmpl("SearchResultPortlet-LinkImg",objParam)));
					
					this.setHighlightKeywords(searchItemPlhld);
					finalResult.push($("<div></div>").append(searchItemPlhld));
				}
				return finalResult;
			},
			
			buildSearchNavigation: function(){
				return this.fetchPageLink();
			},
			
			fetchPageLink: function(){
				var result = $("<div></div>");
				var numPages = parseInt(this.numDocs / this.rows);
				if(numPages == 0){
					numPages = 1;
				}
				var curPage = parseInt(this.searchPage); 
				var pageLinks = Array();
				if (curPage > numPages){
					curPage = numPages;
				}
				if (curPage <= 0){
					curPage = 1;
				}
				
				for(var x = 1; x <= numPages; x ++) {
					if (x == curPage) {
						var objParam = {};
						objParam.content = x;
						pageLinks[x-1] = tmpl("CommonPortlet-NavCurrent",objParam);
					} else {
						var objParam = {};
						objParam.query = this.query;
						objParam.pageType = this.pageType;
						objParam.searchPage = x;
						objParam.content = x;
						objParam.rows = this.rows;
						objParam.searchController = "SearchResult";
						pageLinks[x-1] = tmpl("CommonPortlet-NavOther",objParam);
					}
				}
				
				if (curPage > 1 && curPage <= pageLinks.length){
					var objParam = {};
					objParam.query = this.query;
					objParam.pageType = this.pageType;
					objParam.searchPage = curPage-1;
					objParam.content = "&#171 Trước&nbsp;";
					objParam.rows = this.rows;
					objParam.searchController = "SearchResult";
					result.append(tmpl("CommonPortlet-NavOther",objParam));
				}
				
				
				for (var key= curPage-11; key <= curPage+9; key++ ) {
					if (key<0) continue;
					if (key>= pageLinks.length) continue;
					if (key == curPage)
						result.append(pageLinks[key]);
					else
						result.append(pageLinks[key]);
				}		
				
				if(curPage < pageLinks.length){
					var objParam = {};
					objParam.query = this.query;
					objParam.pageType = this.pageType;
					objParam.searchPage = curPage+1;
					objParam.content = "&nbsp;Sau&nbsp;&#187";
					objParam.rows = this.rows;
					objParam.searchController = "SearchResult";
					result.append(tmpl("CommonPortlet-NavOther",objParam));
				}
				return result;
			},
			
			setHighlightKeywords: function(element){
				element.find("em").addClass("bkp_search_highlight");
			},
			
			getSourcePercentage: function(profileid){
				//ajax
				$.get(
						this.root + 'ajax/get-source-percentage',
						{'id':profileid},
						function(ret)	{
							ret = $.parseJSON(ret);
							if (ret == null)	{
								$('.errorMsg-' + profileid).html('Thông báo: Không lấy được thông tin về nguồn ');
							} else if (ret.result=='error')	{
								$('.errorMsg-' + profileid).html('Thông báo: '+ret.message);
							} else {
								$('.errorMsg-' + profileid).html('');
								$("#vertgraph-"+profileid).empty();
								var leftMargin = 0;
								for(key in ret.result){
									leftMargin += 50;
									var value = ret.result[key].percent;
									var color = ret.result[key].color;
									var objParam = {};
									objParam.name = key;
									objParam.height = Math.round(50 * value);
									objParam.value = Math.round(100 * value*10)/10 + "%";
									objParam.color = color;
									objParam.left = leftMargin;
									var microTemplateBar = tmpl("SearchResultPortlet-sourcePerPlhld",objParam);
									$("#vertgraph-"+profileid).append(microTemplateBar);
								}
							}
							return false;
						}
					);
			},
			
			// done
			normalizeKeyword:function(keyword){
				var ret = keyword.replace("_indexed","");
				ret = ret.replace("_unindexed","");
				return ret;
			},

			// done
			fetchToMainView: function(){
				var id = "SearchResultPortlet-ViewPrefetch";
				var obj = {};
				obj.children = this.buildSearchItems();
				obj.navigator = this.buildSearchNavigation();
				return tmpl(id, obj);
			},
			
			// done
			getSearchItemPlhld: function(){
				var id = this.name + "-Item"+ this.pageType + "-View";
				return tmpl(id, {});
			},
			
			// done
			buildPartialTemplate: function(data, type){
				//single; list; highlightResJSON
				var id = this.name + "-Item" + this.pageType + "-" + type;
				return tmpl(id,data);
			},
			
			// done
			render: function(){
				return this.fetchToMainView();
			},
			
			// done
			run : function() {
				this.getPortletPlaceholder().drawToCanvas(this.render());
				this.loadAjax();
			},
			
			loadAjax: function(){
				// load all ajax here;
				// dump all profile into array
				//console.log("ajax");
				for(var key in this.ajaxProfileArr){
					this.getSourcePercentage(this.ajaxProfileArr[key]);
				}
			},
			
			onEnd: function()	{
				this.unregisterObserver();
			}
		}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface);

